//
//  BwtInterstitialAd.m
//  bwt_ad_flutter
//
//  Created by ciba on 2024/8/29.
//

#import "BwtInterstitialAd.h"
#import <AdSupport/AdSupport.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#import <CXHAdSDK-Core/CXHAdSDKNativeInterstitialAd.h>
#import "BwtAdLogManager.h"

@interface BwtInterstitialAd ()<CXHAdSDKNativeInterstitialAdDelegate>
@property (nonatomic) bool isAdLoaded;
@property (nonatomic) bool isAdShowed;
@property (nonatomic) bool isAdExposed;
@property (nonatomic) bool isAdClosed;
@property (nonatomic) CXHAdSDKNativeInterstitialAd *interstitialAd;

@end

@implementation BwtInterstitialAd

/// 接到Flutter消息，开始加载插屏广告
- (void)loadInterstitialAd {
    if (self.interstitialAd) {
        return;
    }
    [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告加载前检查, adId: %@", _adParams.adId];
    if (_isRequestIdfa && @available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if ([NSThread isMainThread]) {
                [self innerLoadInterstitialAd ];
            } else {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // 非主线程，将UI操作切换到主线程进行，请求广告
                    [self innerLoadInterstitialAd ];
                });
            }
        }];
    } else {
        [self innerLoadInterstitialAd ];
    }
}

/// 真正的请求插屏广告
- (void) innerLoadInterstitialAd {
    if (self.interstitialAd) {
        return;
    }
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *rvc = window.rootViewController;
    
    self.interstitialAd = [[CXHAdSDKNativeInterstitialAd alloc]init];
    self.interstitialAd.delegate = self;
    self.interstitialAd.controller = rvc;
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"正在加载插屏广告, adId: %@", _adParams.adId];
    [self.interstitialAd loadAd:_adParams.posId];
}

/// 接到Flutter消息，尝试展示插屏广告
- (void)showInterstitialAd {
    if(self.isAdLoaded && !self.isAdShowed && self.interstitialAd) {
        self.isAdShowed = true;
        [self.interstitialAd showAdView];
        [[BwtAdLogManager getBwtAdLogManager] log:@"展示插屏广告, adId: %@", _adParams.adId];
    }
}

/// 接到Flutter消息，释放插屏广告
- (void)releaseAd {
    if (self.interstitialAd) {
        self.interstitialAd = nil;
        [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告已释放, adId: %@", _adParams.adId];
    }
}

#pragma mark - CXHAdSDKNativeInterstitialAdDelegate
/// 插屏广告加载成功
- (void)nativeInterstitialAdSuccessToLoad:(CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd {
    [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告加载成功, adId: %@", _adParams.adId];
    self.isAdLoaded = YES;
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadEvent:_adParams];
    
    if(self.interstitialAd && _loadThenShow) {
        [self.interstitialAd showAdView];
    }
}

/// 插屏广告加载失败
- (void)nativeInterstitialAdFailedToLoad:(nonnull CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd error:(nonnull NSError *)error {
    NSString *message = [error localizedDescription];
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告加载成功, adId: %@, error: %@", _adParams.adId, message];
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:message];
    
    [self releaseAd];
}

/// 插屏广告曝光
- (void)nativeInterstitialAdExposure:(CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd {
    if (!self.isAdExposed) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告被展示, adId: %@", _adParams.adId];
        self.isAdExposed = YES;
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdExposeEvent:_adParams];
    }
}

/// 插屏广告被点击
- (void)nativeInterstitialAdClick:(CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd {
    [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告被点击, adId: %@", _adParams.adId];
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdClickEvent:_adParams];
}

/// 插屏广告被关闭
- (void)nativeInterstitialAdClose:(CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd {
    if (!self.isAdClosed) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告被关闭, adId: %@", _adParams.adId];
        self.isAdClosed = YES;
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdCloseEvent:_adParams];
    }
    
    [self releaseAd];
}

- (void)nativeInterstitialAdClick:(nonnull CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd loadingPageURL:(nonnull NSString *)loadingPageURL {
    [[BwtAdLogManager getBwtAdLogManager] log:@"插屏广告被点击, adId: %@", _adParams.adId];
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdClickEvent:_adParams];
}

- (void)nativeInterstitialAdLoadingPageViewClose:(CXHAdSDKNativeInterstitialAd *)nativeInterstitialAd{
    
}

@end
